<?php


namespace app\home\controller;


use app\base\BaseController;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class Warehouse
 * @package app\home\controller
 * 仓库
 */
class Warehouse extends BaseController
{
    protected $table='warehouse';
    protected $title='仓库档案';
    private $sessionKey='pageWarehouse';
    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
            if (request()->isAjax()) {
                $param=$this->param;
                $where[]=['status','>',-1];
                if (isset($this->param['status'])&&$this->param['status']){
                    $where[]=['status','=',$this->param['status']];
                }
                if (isset($this->param['name'])&&$this->param['name']){
                    $where[]=['name','like','%'.$this->param['name'].'%'];
                }
                $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
                $list = Db::name($this->table)
                    ->where($where)
                    ->field('*')
                    ->paginate($rows);
                session($this->sessionKey,$where);
                return table_assign(0, '', $list);
            } else {
                return view();
            }
    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
            $param['update_time']=time();
            if (isset($param['file'])){
                unset($param['file']);
            }
            $wCode=$param['wCode']??'';
            if ($wCode&&!ctype_upper($wCode)){
                return to_assign(1,'参数有误');
            }

            if ($param['id'] > 0) {
                if ($wCode){
                    $isHave=Db::name($this->table)
                        ->where('id','<>',$param['id'])
                        ->where('deleted',0)
                        ->where('wCode',$wCode)->count();
                    if ($isHave){
                        return to_assign(1,'编号已存在');
                    }
                }


                Db::name($this->table)->strict(false)->field(true)->update($param);
                add_log('edit', $param['id'], $param,$this->title);
            } else {
                if ($wCode){
                    $isHave=Db::name($this->table)
                        ->where('deleted',0)
                        ->where('wCode',$wCode)->count();
                    if ($isHave){
                        return to_assign(1,'编号已存在');
                    }
                }

                $param['create_time'] = time();
                $rid = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                add_log('add', $rid, $param,$this->title);
            }
            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                View::assign('detail', $detail);
            }
            View::assign('id', $id);

            return view('form');
        }
    }

    /**
     * date:2024/4/17
     * 详情
     */
    public function detail()
    {
        $param = get_params();
        if (request()->isAjax()) {
            if ($this->request->isPost()){
                $param=$this->param;
                $param['update_time']=time();
               $param['create_time'] = time();
                $rid = Db::name('warehouse_detail')->strict(false)->field(true)->insertGetId($param);
               add_log('add', $rid, $param,$this->title.'->添加明细');

                return to_assign();
            }else{
                $list =Db::name('warehouse_detail')
                    ->where('status','1')
                    ->where('warehouse_id',$param['id'])->select();
                return to_assign(0, '', $list);
            }

        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                View::assign('detail', $detail);
            }
            View::assign('id', $id);

            return view('detail');
        }
}
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    /**
     * date:2024/4/17
     * 删除明细
     */
    public function delMx()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            try {
                Db::name('warehouse_detail')->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title.'->删除明细');
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
}
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/4/1
     * 启用/禁用
     */
    public function doCheck()
    {
        $param = get_params();
        $param['update_time']=time();
        $res = Db::name($this->table)->strict(false)->field('id,status,update_time')->update($param);
        if ($res) {
            if($param['status'] == 2){
                add_log('disable', $param['id'], $param,$this->title);
            }
            else if($param['status'] == 1){
                add_log('recovery', $param['id'], $param,$this->title);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    public function importData()
    {
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {

                        $importData[] = [
                            "name" => $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue(),
                            "deleted" =>0,
                            "create_time"=>time(),
                            'update_time'=>time()
                        ] ;
                }
                if ($importData){
                    Db::name($this->table)->insertAll($importData);
                    add_log('import', '', $importData,$this->title);
                }

            }
        }catch (Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }

    public function importMx()
    {
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            $id=$this->param['id']??'0';
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (!$id){
                throw new Exception('参数缺失');
            }
            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {

                    $importData[] = [
                        "name" => $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue(),
                        "deleted" =>0,
                        "warehouse_id" =>$id,
                        "create_time"=>time(),
                        'update_time'=>time()
                    ] ;
                }
                if ($importData){
                    Db::name('warehouse_detail')->insertAll($importData);
                    add_log('import', '', $importData,$this->title.'->导入明细');
                }

            }
        }catch (Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)
            ->where($where)
            ->field('*')->select()->each(function ($item){
                $item['status']=$item['status']==1?'正常':'禁用';
                return $item;
            });
        $title = [
            'name' => '仓库名称',
            'wCode' => '仓库简称',
            'status' => '状态',
        ];
        $name = "仓库档案";
        exportXlsData($name,$title,$list);
        exit();
    }
}